<?php

namespace app\api\service;
/**
 * Created by PhpStorm.
 * User: chency
 * Date: 2018/11/10 0010
 * Time: 下午 1:56
 */
class BaiduService {
    //API控制台申请得到的ak
    private $ak = 'gguUxZbSQPimXfsMumTGGD7Resxr3rLb';

    //应用类型为for server, 请求校验方式为sn校验方式时，系统会自动生成sk，可以在应用配置-设置中选择Security Key显示进行查看（此处sk值仅供验证参考使用）
    private $sk = 'euTgAsftt9txWHPStISyBWWe0U7pyt8q';

    private $sn = '';

    private function calcAKSN($sk, $url, $data, $method = 'GET') {
        if ($method === 'POST') {
            ksort($data);
        }
        $queryString = http_build_query($data);
        return md5(urlencode($url . '?' . $queryString . $sk));
    }

    public function getAddressByIp($ip) {
        $url  = 'https://api.map.baidu.com/location/ip';
        $uri  = '/location/ip';
        $data = [
            'ip'   => urlencode($ip),
            'ak'   => $this->ak,
            'coor' => 'bd09ll'
        ];
        ksort($data);
        $this->sn   = $this->calcAKSN($this->sk, $uri, $data);
        $data['sn'] = $this->sn;
        ksort($data);
        $ret = https_request($url, $data);
        return json_decode($ret, true);
    }

    public function getTransitByOriginAndDestination($origin, $destination) {
        $url  = 'http://api.map.baidu.com/direction/v2/transit';
        $uri  = '/direction/v2/transit';
        $data = [
            'origin'        => $origin,
            'destination'   => $destination,
            'coord_type'    => 'bd09ll',
            'ret_coordtype' => 'bd09ll',
            'output'        => 'json',
            'timestamp'     => time(),
        ];
        ksort($data);
        $this->sn   = $this->calcAKSN($this->sk, $uri, $data);
        $data['sn'] = $this->sn;
        ksort($data);
        $ret = https_request($url, $data);
        return json_decode($ret, true);
    }
}